package com.minosiants.dann.service
import org.scribe.model.Token

import org.scribe.model.Verifier


import com.minosiants.dann.data._
import com.minosiants.dann.repository._;import org.scribe.builder.ServiceBuilder
import org.scribe.builder.api.TwitterApi
import org.scribe.oauth._
trait OauthService{
	
}

class OauthServiceImpl(service:OAuthService,repository:Repository){
	  /* = new ServiceBuilder()
                                  .provider(classOf[TwitterApi])
                                  .apiKey("1sikeGafLvmGtTSvIXv78A")
                                  .apiSecret("oVcqU2sLx39OqN9VQn2IgjOAlHwobqLZ4XCfiG8p3E")
                                  .build();*/
                                  
                                  
    def authorizationUrlFor(userId:String):String={
		 val requestToken = service.getRequestToken()
		 saveRequestToken(userId,requestToken.getToken,requestToken.getSecret) 
		 service.getAuthorizationUrl(requestToken)
	}
    def verify(userId:String,verifier:String){
      oauthData(userId) match{
    		case None =>
    		case Some(s)=>{
    			val accessToken=service.getAccessToken(new Token(s.requestToken,s.requestSecret),new Verifier(verifier))
    			s.accessSecret=accessToken.getSecret
    			s.accessToken=accessToken.getToken
    			s.verifier=verifier
    			repository.save(s)
    		}
      }//try implicit
      
    } 
   
    private def oauthData(userId:String):Option[OauthData]={
      repository.findOne(OauthDataQuery(Map("userId"->userId))).asInstanceOf[Option[OauthData]]
    }
    private def saveRequestToken(userId:String,requestToken:String,requestSecret:String){
    	val o=new OauthData;
    	o.userId=userId
    	o.requestToken=requestToken
    	o.requestSecret=requestSecret
    	oauthData(userId) match{
    		case None =>repository.save(o)
    		case Some(s)=>repository.save(OauthData.merge(s.asInstanceOf[OauthData],o))
    	}
    } 
}

case class OauthDataQuery(override val queryObject:Map[String,Object],
						  override val numToSkip: Int=0, 
						  override val batchSize: Int=0) 
						  extends  Query[OauthData](OauthData.collectionName,queryObject,classOf[OauthData],numToSkip,batchSize);

object OauthDataQuery{
	def apply(queryObject:Map[String,Object])=new OauthDataQuery(queryObject)
}